package com.sky.socket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;

/**
 * webSocket服务类
 */
@Component
@ServerEndpoint("/ws/{sid}")
@Slf4j
public class WebSocketServer {
    private static HashMap<String,Session> map = new HashMap<>();
    @OnOpen
    //建立连接的回调方法
    public void onOpen(Session session, @PathParam("sid") String sid) {
        System.out.println("客户端：" + sid + "建立连接");
        map.put(sid,session);
    }
    @OnMessage
    //收到客户端消息的回调方法
    public void OnMessage(String msg, @PathParam("sid") String sid) {
        System.out.println("客户端：" + sid + "发来消息:"+msg);
    }
    @OnClose
    //建立连接的回调方法
    public void onClose(@PathParam("sid") String sid) {
        System.out.println("客户端：" + sid + "已关闭");
        map.remove(sid);
    }


    //群发消息
    public void sendToAllServer(String msg) {
        Collection<Session> sessions = map.values();
        if(!sessions.isEmpty()) {
            sessions.forEach(session -> {
                try {
                    //向客户端发送消息
                    session.getBasicRemote().sendText(msg);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }



}
